<template>
  <div class="works-review-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>作品审核管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.worksName"
            placeholder="请输入作品名称搜索"
            allow-clear
            @pressEnter="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.description"
            placeholder="请输入作品描述搜索"
            allow-clear
            @pressEnter="handleSearch"
          />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch">
            <SearchOutlined />
            搜索
          </a-button>
        </a-col>
        <a-col :span="4">
          <a-button @click="resetSearch"> 重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 列表区域 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        bordered
      >
        <!-- 作品名称列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'worksName'">
            {{ record.worksName }}
          </template>

          <!-- 封面图渲染 -->
          <template v-else-if="column.key === 'coverFileUrl'">
            <div class="cover-img-container">
              <img
                v-if="record.coverFileUrl"
                :src="minioUrl + record.coverFileUrl"
                alt="作品封面"
                class="cover-img"
              />
              <span v-else class="no-cover">无封面</span>
            </div>
          </template>

          <!-- 状态标签渲染 -->
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <!-- 是否收费渲染 -->
          <template v-else-if="column.key === 'isCharge'">
            <a-tag :color="record.isCharge === 1 ? 'blue' : 'green'">
              {{ record.isCharge === 1 ? '收费' : '免费' }}
            </a-tag>
          </template>

          <!-- 操作列渲染 -->
          <template v-else-if="column.key === 'action'">
            <a-space size="small">
              <a-button type="primary" size="small" @click="handleAudit(record)"> 审核</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 审核弹窗（含视频播放） -->
    <!-- 审核弹窗（含视频播放） -->
    <a-modal
      v-model:open="auditModalVisible"
      title="作品审核"
      width="800px"
      @ok="confirmAudit"
      @cancel="handleCancelAudit"
    >
      <div v-if="currentWork" class="audit-modal-content">
        <!-- 视频播放区域 -->
        <div class="audit-video-container">
          <video
            v-if="currentWork.videoUrl"
            :src="minioUrl + currentWork.videoUrl"
            controls
            class="audit-video"
            :poster="minioUrl + currentWork.coverFileUrl"
          >
            您的浏览器不支持视频播放
          </video>
          <div v-else class="no-video">暂无视频资源</div>
        </div>

        <!-- 作品基本信息 -->
        <div class="audit-work-info">
          <h3>{{ currentWork.worksName }}</h3>
          <p class="audit-work-desc">{{ currentWork.description || '无描述' }}</p>

          <div class="audit-work-meta">
            <p><span class="meta-label">创建时间：</span>{{ currentWork.createTime }}</p>
            <p><span class="meta-label">作者：</span>{{ currentWork.username || '未知' }}</p>
            <p>
              <span class="meta-label">当前状态：</span>
              <a-tag :color="getStatusColor(currentWork.status)">
                {{ getStatusText(currentWork.status) }}
              </a-tag>
            </p>
          </div>
        </div>

        <!-- 审核操作区域 -->
        <div class="audit-result-group">
          <a-radio-group v-model:value="auditResult" class="audit-radio-group">
            <a-radio :value="1">通过</a-radio>
            <a-radio :value="2">驳回</a-radio>
          </a-radio-group>

          <a-textarea
            v-model:value="auditRemark"
            placeholder="请输入审核意见（驳回时必填）"
            :rows="4"
            class="audit-remark"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { getWorksReviewList } from '@/api/media/bizWorksController'
import { useTagStore } from '@/stores/worksTagStore'
import { worksContentReview } from '@/api/media/bizContentReviewController'

// 假设存在审核接口，实际请替换为你的真实接口
// import { auditWork } from "@/api/media/bizWorksController";

// 状态管理
const loading = ref(false)
const tableData = ref([])
const auditModalVisible = ref(false)
const currentWork = ref(null)
const minioUrl = import.meta.env.VITE_MINIO_URL
const tagStore = useTagStore()

// 搜索表单
const searchForm = reactive({
  worksName: '', // 作品名称
  description: '', // 作品描述
  pageNum: 1, // 页码
  pageSize: 10, // 每页条数
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`,
  pageSizeOptions: ['10', '20', '50', '100'],
})

// 审核表单数据
const auditResult = ref(1) // 1:通过 2:驳回
const auditRemark = ref('')

// 表格列配置
const columns = [
  {
    title: '作品名称',
    dataIndex: 'worksName',
    key: 'worksName',
    width: 150,
    ellipsis: true,
    align: 'center',
  },
  {
    title: '作品封面',
    key: 'coverFileUrl',
    width: 120,
    align: 'center',
  },
  {
    title: '作品描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
    ellipsis: true,
    align: 'center',
  },
  // {
  //   title: '标签',
  //   dataIndex: 'tags',
  //   key: 'tags',
  //   width: 150,
  //   align: 'center'
  // },
  {
    title: '是否收费',
    key: 'isCharge',
    width: 100,
    align: 'center',
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100,
    align: 'center',
  },
  {
    title: '状态',
    key: 'status',
    width: 120,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center',
  },
]

// 获取作品列表数据
const loadWorksList = async () => {
  loading.value = true
  try {
    // 调用接口获取列表数据
    const response = await getWorksReviewList(searchForm)

    if (response.code === '00000') {
      tableData.value = response.data.list || []
      console.log(tableData.value)
      pagination.total = response.data.total || 0
    } else {
      message.error(`获取数据失败：${response.message || '未知错误'}`)
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取作品列表失败：', error)
    message.error('网络异常，获取作品列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  searchForm.pageNum = 1
  pagination.current = 1
  loadWorksList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.worksName = ''
  searchForm.description = ''
  searchForm.pageNum = 1
  pagination.current = 1
  loadWorksList()
}

// 分页变化处理
const handleTableChange = (paginationObj) => {
  searchForm.pageNum = paginationObj.current
  searchForm.pageSize = paginationObj.pageSize
  pagination.current = paginationObj.current
  pagination.pageSize = paginationObj.pageSize
  loadWorksList()
}

// 状态文本映射（根据实际业务调整）
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '审核中',
    3: '审核通过',
    4: '审核驳回',
    5: '已发布',
  }
  return statusMap[status] || `未知(${status})`
}

// 状态颜色映射（根据实际业务调整）
const getStatusColor = (status) => {
  const colorMap = {
    0: 'orange', // 草稿
    1: 'gold', // 待审核
    2: 'purple', // 审核中
    3: 'green', // 审核通过
    4: 'red', // 审核驳回
    5: 'blue', // 已发布
  }
  return colorMap[status] || 'gray'
}

// 打开审核弹窗
const handleAudit = (record) => {
  currentWork.value = { ...record }
  auditResult.value = 1 // 默认通过
  auditRemark.value = ''
  auditModalVisible.value = true
}

// 确认审核
// 确认审核（修改后的完整逻辑）
const confirmAudit = async () => {
  if (!currentWork.value) return

  // 验证：驳回时必须填写审核意见
  if (auditResult.value === 2 && !auditRemark.value.trim()) {
    message.warning('请输入驳回理由')
    return
  }

  // 构造接口参数（严格对应 ContentReviewQuery 类型）
  const reviewParams = {
    worksId: currentWork.value.id, // 作品ID（必填）
    manualReviewRemark: auditRemark.value.trim(), // 审核意见（驳回时必填）
    reviewStatus: auditResult.value, // 审核状态：1-通过，2-驳回
  }

  loading.value = true
  try {
    // 调用审核接口
    const response = await worksContentReview(reviewParams)

    if (response.code === '00000') {
      message.success('审核操作成功')
      auditModalVisible.value = false
      loadWorksList() // 重新加载列表，刷新状态
    } else {
      message.error(`审核失败：${response.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('审核接口调用失败：', error)
    message.error('网络异常，审核操作失败')
  } finally {
    loading.value = false
  }
}

// 取消审核
const handleCancelAudit = () => {
  auditModalVisible.value = false
  currentWork.value = null
  auditRemark.value = ''
}

// 页面初始化加载数据
onMounted(() => {
  loadWorksList()
})
</script>

<style scoped>
.works-review-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 20px;
}

.page-title h2 {
  margin: 0;
  color: #1f2329;
  font-size: 18px;
  font-weight: 600;
}

.search-container {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.table-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 封面图样式 */
.cover-img-container {
  width: 80px;
  height: 50px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #eee;
}

.cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
  background-color: #f5f5f5;
}

/* 审核弹窗样式 */
.audit-modal-content {
  padding: 10px 0;
}

.audit-work-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.audit-work-info h3 {
  margin: 0 0 10px 0;
  color: #1f2329;
}

.audit-work-desc {
  color: #666;
  line-height: 1.5;
  margin: 0 0 15px 0;
  font-size: 14px;
}

.audit-work-meta {
  font-size: 14px;
}

.meta-label {
  color: #86909c;
  display: inline-block;
  width: 80px;
}

.audit-result-group {
  margin-top: 15px;
}

.audit-radio-group {
  margin-bottom: 15px;
}

.audit-remark {
  width: 100%;
}

/* 视频容器样式 */
.audit-video-container {
  width: 100%;
  background-color: #000;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 360px; /* 固定视频区域高度，避免内容跳动 */
}

/* 视频样式 */
.audit-video {
  width: 100%;
  max-height: 400px; /* 限制最大高度，适配弹窗 */
  object-fit: contain; /* 保持视频比例，避免拉伸 */
}

/* 无视频提示样式 */
.no-video {
  color: #fff;
  padding: 20px;
  text-align: center;
}

/* 调整信息区域与视频的间距 */
.audit-work-info {
  margin: 20px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
</style>
